package com.ujiuye.service;

import com.ujiuye.pojo.Permission;
import com.ujiuye.pojo.Role;
import com.ujiuye.pojo.User;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private IUserService userService;
    @Reference
    private IRoleService roleService;
    @Reference
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUserName(username);
        if (user == null){
            throw new UsernameNotFoundException("没有该用户");
        }
        List<Role> roleList = roleService.listByUserId(user.getId());//角色
        List<Permission> permissionList = permissionService.listByUserId(user.getId());//权限
        List<GrantedAuthority> authorityList = new ArrayList<>();//保存角色和权限的集合
        for (Role role : roleList) {
            authorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
        }
        for (Permission permission : permissionList) {
            authorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorityList);
    }
}
